package com.truing.flycodebill.settings.web.controller;

import com.truing.flycodebill.commons.constant.Constant;
import com.truing.flycodebill.commons.domain.ReturnObject;
import com.truing.flycodebill.commons.utils.UUIDUtil;
import com.truing.flycodebill.settings.domain.User;
import com.truing.flycodebill.settings.service.UserService;
import com.truing.flycodebill.workbench.domain.Bill;
import com.truing.flycodebill.workbench.service.BillService;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@ResponseBody
@CrossOrigin
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private BillService billService;

    /**
     * ---黄宇瀚 2022年5.12日晚上10点
     * 用户登录
     * 方法需要实现：
     * 1、将前台接收的userName和password封装为Map
     * 2、调用UserService查询数据库，根据返回值确定是否登录成功并将登录信息加入到ReturnObject返回给前台
     * 3、根据用户的isRemPwd判断用户是否记住密码
     *
     * @param loginAct
     * @param loginPwd
     * @param isRemPwd
     * @param response
     * @param session
     * @return
     */
    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public Object login(String loginAct, String loginPwd, String isRemPwd, HttpServletResponse response, HttpSession session) {
        //获取参数
        System.out.println(loginAct);
        System.out.println(loginPwd);
        //封装参数
        HashMap<String, Object> map = new HashMap<>();
        map.put("loginAct",loginAct);
        map.put("loginPwd",loginPwd);
        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层完成任务
            User user = userService.queryUserByLoginActAndPwd(map);
            //        如果用户为空，则说明用户不存在
            if (user == null) {
                //用户不存在，
                returnObject.setCode(Constant.RETURN_OBJECT_CODE_FAIL);
            }else {
                returnObject.setCode(Constant.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("登录成功");
                returnObject.setReturnData(user);
                //如果用户存在，则将用户情况加入到session域中
                session.setAttribute(Constant.SESSION_USER,user);
                //判断是否记住密码
                if (Constant.IS_REM_PWD_YES.equals(isRemPwd)) {
                    //发送两个Cookie
                    Cookie userNameCookie = new Cookie(Constant.COOKIE_NAME,user.getLoginAct());
                    userNameCookie.setMaxAge(10*24*60*60);
                    Cookie passwordCookie = new Cookie(Constant.COOKIE_PASSWORD,user.getLoginPwd());
                    passwordCookie.setMaxAge(10*24*60*60);
                    response.addCookie(userNameCookie);
                    response.addCookie(passwordCookie);
                }else {
                    //用户没有选择记住密码，那就覆盖原来的cookie
                    Cookie userNameCookie = new Cookie(Constant.COOKIE_NAME,"0");
                    userNameCookie.setMaxAge(0);
                    Cookie passwordCookie = new Cookie(Constant.COOKIE_PASSWORD,"0");
                    passwordCookie.setMaxAge(0);
                    response.addCookie(userNameCookie);
                    response.addCookie(passwordCookie);
                }
            }
        } catch (Exception e) {
            returnObject.setCode(Constant.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙稍后重试");
        }
        //根据返回结果，生成响应信息
        System.out.println(returnObject.getCode());
        return returnObject;

    }

    /**
     * ---黄宇瀚 2022年5.12日晚上10点
     * 用户退出登录
     *  方法需要实现：
     *      1、清空cookie
     *      2、销毁session
     *      3、通知前端跳转页面
     * @param response
     * @param session
     * @return
     */
    @RequestMapping("/logout.do")
    public Object logout(HttpServletResponse response,HttpSession session){
        //接收擦书，封装参数
        //session域处理
        ReturnObject returnObject = new ReturnObject();
        try {
            session.invalidate();
            //cookie处理,全部覆盖
            Cookie loginActCookie = new Cookie(Constant.COOKIE_NAME, "0");
            loginActCookie.setMaxAge(0);
            Cookie loginPwdCookie = new Cookie(Constant.COOKIE_PASSWORD, "0");
            loginPwdCookie.setMaxAge(0);
            //将cookie加入response返回给浏览器
            response.addCookie(loginActCookie);
            response.addCookie(loginPwdCookie);
            //设置退出成功
            returnObject.setCode(Constant.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setMessage("退出成功");
        } catch (Exception e) {
            //生成响应信息
            //退出失败，报错
            returnObject.setCode(Constant.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试...");

        }
        return returnObject;
    }

    /**
     * 根据用户id查询用户信息，返回给前台，用于展现在客户个人中心
     * @param id
     * @return
     */
    @RequestMapping("/queryUserInformation.do")
    public Object queryUserInformation(String id){
        ReturnObject returnObject = new ReturnObject();
        Map<String,Object> map = new HashMap<>();
        int expend = 0;
        int incoming = 0;
        try {
            User user =  userService.queryUserById(id);
            if (user != null){
                returnObject.setCode(Constant.RETURN_OBJECT_CODE_SUCCESS);
                map.put("ownerId",user.getId());
                map.put("typeId","1");
                List<Bill> extendBillList = billService.queryBillsByTypeId(map);
                for (Bill bill : extendBillList){
                    expend+=Integer.parseInt(bill.getPrice());
                }
                map.put("typeId","2");
                List<Bill> incomingBillList = billService.queryBillsByTypeId(map);
                for (Bill bill : incomingBillList){
                    incoming+=Integer.parseInt(bill.getPrice());
                }
                int assets = Integer.parseInt(user.getBalance())+incoming-expend;
                returnObject.setMessage(Integer.toString(assets));
                returnObject.setReturnData(user);
            }else {
                returnObject.setCode(Constant.RETURN_OBJECT_CODE_FAIL);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return returnObject;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @RequestMapping("/register.do")
    public Object register(User user){
        user.setId(UUIDUtil.getUUID());
        ReturnObject returnObject = new ReturnObject();
        try {
            int ret = userService.saveCreateUser(user);
            if (ret > 0){
                returnObject.setCode(Constant.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("注册成功");
                returnObject.setReturnData(user);
            }else {
                returnObject.setCode(Constant.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试...");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return returnObject;
    }
}
